#include "mainwindow.h"
#include "toast.h"
#include "ui_mainwindow.h"
#include <QTimer>
#include <QList>
#include <opencv2/opencv.hpp>
#include <QDockWidget>
#include <QFileDialog>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 申请权限
    Permission();

    ui->tabWidget->addTab(&myCamera, "相机");

    // 相机类和扫码回调
    connect(&myCamera, SIGNAL(in_return_text(QString)), this, SLOT(in_get_return_text(QString)));

    // // //表格
    standItemModel = new QStandardItemModel();
    ui->tableView->setModel(standItemModel);    //挂载表格模型
    // 设置表格属性
    ui->tableView->horizontalHeader()->setDefaultAlignment(Qt::AlignCenter);            //表头信息显示居中
    ui->tableView->setEditTriggers(QAbstractItemView::SelectedClicked);                 //设置表格属性(如只读，不能编辑)
    mainCSV.UpdateCache(standItemModel);
    ui->tableView->resizeColumnsToContents();
    ui->tableView->scrollToBottom();

    // // lineEdit
#ifndef WIN32
    // // //刷新界面
    QTimer *timer = new QTimer(this);
    timer->setInterval(100);
    connect(timer, &QTimer::timeout, [=]{
        this->update();
    });
    timer->start();
#endif
    QTimer::singleShot(0, this, [=](){
        ui->lineEdit->SetIsDownKeyBoard(1);
    });

}

MainWindow::~MainWindow()
{
    delete ui;
    ui->tabWidget->widget(1)->deleteLater();
    standItemModel->deleteLater();
}

void MainWindow::on_pushButton_clicked()
{
    // 打开相机
    myCamera.CameraInit();
    myCamera.startCamera();
    ui->tabWidget->setCurrentWidget(&myCamera);
}

void MainWindow::in_get_return_text(QString barcodeText)
{
    ui->lineEdit->setText(barcodeText);
    InputToTable();
    if(ui->action8->isChecked()){
        QTimer::singleShot(500, this, [=](){
            myCamera.Pause(0);
            ui->tabWidget->setCurrentIndex(1);
        });
    }
}


void MainWindow::InputToTable()
{
    QString text = ui->lineEdit->text();
    if(text.isEmpty()){
        Toast::instance().show(Toast::WARN, "输入框内容为空!", this);
        return;
    }
    // 获取选中的列，数据插入到列中
    QModelIndex currentIndex = ui->tableView->selectionModel()->currentIndex();
    int currentRow = currentIndex.row(),
        currentColumn=currentIndex.column();
    if (currentIndex.isValid()) {
        standItemModel->setItem(currentRow, currentColumn, new QStandardItem(text));
    }else{
        if(QMessageBox::Yes==QMessageBox::warning(this, u8"警告", u8"未选择一个单元格以知道要插入那一列，是否插入第一列？", QMessageBox::Yes|QMessageBox::No, QMessageBox::No)){
            standItemModel->setItem(standItemModel->rowCount(), 0, new QStandardItem(text));
            currentRow = standItemModel->rowCount()-1;
            currentColumn = 0;
        }else return;
    }
    //
    ui->tabWidget->setCurrentIndex(0);
    // 如果是最后一行，则添加行
    if(currentRow+1==standItemModel->rowCount())
        standItemModel->setItem(currentRow+1, currentColumn, new QStandardItem(""));
    // 自动跳转选中下一个单元格
    QModelIndex index = ui->tableView->model()->index(currentRow+1, currentColumn);
    QItemSelection selection;
    selection.select(index, index);
    ui->tableView->selectionModel()->select(selection, QItemSelectionModel::ClearAndSelect);
    ui->tableView->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
    ui->tableView->scrollTo(index);
    mainCSV.SaveCache(standItemModel);
    ui->lineEdit->setText("");
}

void MainWindow::on_action1_triggered()
{
    standItemModel->clear();
#ifdef WIN32
    QString selectedFile = QFileDialog::getOpenFileName(this, "Open File", QDir::homePath(), "Text files (*.csv);");
#else
    QString selectedFile = QFileDialog::getOpenFileName(this, "Open File", QDir::homePath(), "*");
    if(selectedFile.indexOf("com.android.providers.media.documents")!=-1||selectedFile.indexOf("com.android.providers.downloads.documents")!=-1){
        QMessageBox::information(this, u8"错误！", u8"请通过sd卡选择文件(不能通过\"图片\"、\"下载\"...来选择文件)。");
        return;
    }
#endif
    if (!selectedFile.isEmpty()) {
        if(selectedFile.right(4)!=".csv"){
            Toast::instance().show(Toast::ERROR, "请打开csv格式文件！", this);
            return;
        }
        mainCSV.ReadCSVFile(selectedFile, standItemModel);
        mainCSV.SaveCache(standItemModel);
        ui->tableView->resizeColumnsToContents();
        ui->tableView->scrollToBottom();
    }
}

void MainWindow::on_action2_triggered()
{
#ifdef WIN32
    QString filter = "csv files (*.csv);";
#else
    QString filter = "*";
#endif
    QString selectedFile = QFileDialog::getSaveFileName(this, "Save File", QDir::homePath(), filter);
    if (!selectedFile.isEmpty()) {
        QFile file(selectedFile);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
            return;
        }
        QTextStream out(&file);
        for (int r = 0; r < standItemModel->rowCount(); ++r) {
            for (int c = 0; c < standItemModel->columnCount(); ++c) {
                auto model =standItemModel->index(r,c).data();
                if(model.isValid()){
                    QString str=model.toString();
                    // 换行符和逗号处理
                    str.replace("\n", "\t");
                    str.replace(",", "[DH]");
                    out << str;
                }
                else
                    out << "";
                if (c < standItemModel->columnCount() - 1) {
                    out << ",";
                }
            }
            out << "\n";
        }
        file.close();
    }
}

// 输入框回车
void MainWindow::on_lineEdit_returnPressed()
{
    if(0==ui->spinBox->value()){
        ui->lineEdit->setText(ui->lineEdit->text()+"\n");
        return;
    }else if(enterNum+1==ui->spinBox->value()){
        InputToTable();
        enterNum = 0;
        return;
    }
    ui->lineEdit->setText(ui->lineEdit->text()+"\n");
    enterNum++;
}

// 清空表格内容
void MainWindow::on_action3_triggered()
{
    QItemSelectionModel* selectionModel = ui->tableView->selectionModel();
    QModelIndexList selectedIndexes = selectionModel->selectedIndexes();
    QVariant emptyData = QString("");
    foreach (QModelIndex index, selectedIndexes) {
        ui->tableView->model()->setData(index, emptyData);
    }
    mainCSV.SaveCache(standItemModel);
}

// 添加表格列
void MainWindow::on_action4_triggered()
{
    int num=standItemModel->columnCount();
    standItemModel->setItem(0, num, new QStandardItem(""));
    ui->tableView->scrollTo(standItemModel->index(0, num));
    mainCSV.SaveCache(standItemModel);
}

// 添加表格行
void MainWindow::on_action6_triggered()
{
    int num=standItemModel->rowCount();
    standItemModel->setItem(num, 0, new QStandardItem(""));
    ui->tableView->scrollTo(standItemModel->index(num, 0));
    mainCSV.SaveCache(standItemModel);
}

// 删除选中表格列
void MainWindow::on_action5_triggered()
{
    ui->tableView->setUpdatesEnabled(false);
    QItemSelectionModel *selectionModel = ui->tableView->selectionModel();
    // 删除后重新获取选中行列，一个一个删避免索引变化导致的问题
    QModelIndexList selectedColumns = selectionModel->selectedColumns();
    while (!selectedColumns.empty()) {
        standItemModel->removeColumn(selectedColumns.at(0).column());
        selectedColumns = selectionModel->selectedColumns();
    }
    // 重新启用视图更新
    ui->tableView->setUpdatesEnabled(true);
    // 刷新视图
    ui->tableView->update();
    mainCSV.SaveCache(standItemModel);
}

// 删除选中表格行
void MainWindow::on_action7_triggered()
{
    ui->tableView->setUpdatesEnabled(false);
    QItemSelectionModel *selectionModel = ui->tableView->selectionModel();
    // 删除后重新获取选中行列，一个一个删避免索引变化导致的问题
    QModelIndexList selectedRows = selectionModel->selectedRows();
    while (!selectedRows.empty()) {
        standItemModel->removeRow(selectedRows.at(0).row());
        selectedRows = selectionModel->selectedRows();
    }
    // 重新启用视图更新
    ui->tableView->setUpdatesEnabled(true);
    // 刷新视图
    ui->tableView->update();
    mainCSV.SaveCache(standItemModel);
}

void MainWindow::on_action8_triggered(bool checked)
{
    Toast::instance().show(Toast::INFO, checked?"自动扫码已开启。":"自动扫码已关闭！", this);
}

void MainWindow::on_action9_triggered(bool checked)
{
    ui->lineEdit->SetIsDownKeyBoard(checked);
    Toast::instance().show(Toast::INFO, checked?"已禁止弹出键盘输入法!":"已允许弹出键盘输入法。", this);
}

void MainWindow::on_tabWidget_currentChanged(int index)
{
    if(index!=0){
        ui->stackedWidget->hide();
        ui->toolBar->setEnabled(false);
        if(!ui->action8->isChecked())
            myCamera.startCamera();
    }else{
        ui->stackedWidget->show();
        ui->toolBar->setEnabled(true);
        if(!ui->action8->isChecked())
            myCamera.stopCamera();
    }
}

